package com.xxkj.drugtraceability.ui.start

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.refactor.ext.versionName
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.RequestBodyData
import com.xxkj.drugtraceability.bean.VersionRequest
import com.xxkj.drugtraceability.databinding.ActivityStartBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.UpdateDialog
import com.xxkj.drugtraceability.ui.drugstorage.DrugStorageActivity
import com.xxkj.drugtraceability.ui.login.LoginActivity
import com.xxkj.drugtraceability.ui.main.MainActivity
import com.xxkj.drugtraceability.ui.update.UpdateActivity
import com.xxkj.drugtraceability.utils.toast
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/9 14:52
 * description:
 */
class StartActivity:BaseVMActivity() {
    private val binding by binding<ActivityStartBinding>(R.layout.activity_start)
    private val viewModel by viewModel<StartViewModel>()
    override fun initView() {

    }

    override fun initData() {
        viewModel.checkVersion(Gson().toJson( VersionRequest(versionName)))
    }

    override fun startObserve() {
        viewModel.upType.observe(this, Observer {
            when(it){
                1->{
                    //升级
                    if (viewModel.drugPdaClientVersion!=null){
                        var type = 0
                        if (viewModel.drugPdaClientVersion!!.updateType=="0"){
                            type = 0
                        }else if (viewModel.drugPdaClientVersion!!.updateType=="1"){
                            type = 2
                        }
                        UpdateDialog(this,viewModel.drugPdaClientVersion!!.description,title = "版本升级",type = type,cancelButtonName = "去升级",action2 = {
                            startActivity(Intent(this, LoginActivity::class.java))
                            finish()
                        },action = {
                            updateApk(viewModel.drugPdaClientVersion!!.fileName)
                        })
                    }
                }
                2->{
                    //不升级
                    startActivity(Intent(this, LoginActivity::class.java))
                    finish()
                }
            }
        })
    }
   private fun updateApk(fileName:String){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

                // Android 6.0 及以上需要申请写入外部存储权限
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION
                )
            } else {
                // 权限已授予，开始文件下载
                startFileDownload()
            }
        } else {
            // 如果是 Android 6.0 以下，直接开始文件下载
            startFileDownload()
        }

    }
    // 权限请求回调结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限已授予，开始文件下载
                    startFileDownload()
                } else {
                    // 权限被拒绝，提示用户
                    println("权限被拒绝，无法下载文件到外部存储。")
                }
            }
        }
    }

    private fun startFileDownload() {
        startActivity(Intent(this,UpdateActivity::class.java).putExtra("fileName",viewModel.drugPdaClientVersion!!.fileName).putExtra("fileUrl",viewModel.drugPdaClientVersion!!.fileUrl))
        finish()
    }

    companion object {
        const val REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 100
    }


}